const express = require('express')
const router = express.Router()
const model = require('../model')
const Chat = model.getModel('chat')

router.get('/data', (req, res, next) => {
    const { userId } = req.cookies
    Chat.find({'$or': [{from: userId}, {to: userId}]}, (err, docs) => {
        if(err) return next(err)
        res.json({code: 0, messages: docs})
    })
})

router.post('/update', (req, res, next) => {
    const { userId } = req.cookies
    const { from } = req.body
    Chat.updateMany({ from, to: userId }, { read: true }, (err, doc) => {
        if(err) return next(err)
        res.json({code: 0, num: doc.nModified })
    })
})

router.get('/remove', (req, res, next) => {
    Chat.remove({}, (err, desc) => {
        if(err) return next(err)
        res.json({code: 0})
    })
})

module.exports = router